package com.apps.ftapp.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.afollestad.materialdialogs.MaterialDialog;
import com.apps.ftapp.R;
import com.apps.ftapp.activity.BanxingActivity;
import com.apps.ftapp.activity.BookActivity;
import com.apps.ftapp.activity.BookDetailActivity;
import com.apps.ftapp.activity.LessonDetailActivity;
import com.apps.ftapp.activity.LianXiActivity;
import com.apps.ftapp.activity.SubjectMoreActivity;
import com.apps.ftapp.activity.TimeTableActivity;
import com.apps.ftapp.activity.ZhenTiNewActivity;
import com.apps.ftapp.adapter.BanXingAdapter;
import com.apps.ftapp.adapter.HomeBookAdapter;
import com.apps.ftapp.adapter.ShiTingAdapter;
import com.apps.ftapp.adapter.TestAdapter;
import com.apps.ftapp.adapter.TiKuAdapter;
import com.apps.ftapp.bean.BookBean;
import com.apps.ftapp.bean.CategoriesBean;
import com.apps.ftapp.bean.ShiTing;
import com.apps.ftapp.bean.TestpapersBean;
import com.apps.ftapp.custom.NoScrollGridView;
import com.apps.ftapp.loader.GlideImageLoader;
import com.apps.ftapp.model.IndexModel2;
import com.apps.ftapp.model.LessonModel;
import com.apps.ftapp.model.TableModel;
import com.apps.ftapp.ui.ExamActivity;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.BroadCastManager;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.DensityUtils;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.SharedPreferencesUtil;
import com.apps.ftapp.util.Tools;
import com.apps.ftapp.view.NoScrollListView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cz.msebera.android.httpclient.Header;


public class NewHomeFragment2 extends Fragment {


    @BindView(R.id.newRefreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.index_btn_rel)
    RelativeLayout index_rel;
    @BindView(R.id.index_btn)
    TextView topTitle;
    @BindView(R.id.zige)
    ImageView zige;
    @BindView(R.id.zixue)
    ImageView zixue;
    @BindView(R.id.main_rel)
    RelativeLayout time_rel;
    @BindView(R.id.shiting)
    NoScrollGridView shitingGrid;
    @BindView(R.id.banxing)
    NoScrollGridView banxingGrid;
    @BindView(R.id.tikugrid)
    NoScrollGridView tkgrid;
    @BindView(R.id.bookgrid)
    NoScrollGridView bookgrid;
    @BindView(R.id.picgroup)
    LinearLayout linearLayout;
    @BindView(R.id.testlist)
    NoScrollListView testListView;

    @BindView(R.id.bx_lin)
    LinearLayout bx_lin;

    @BindView(R.id.tk_lin)
    LinearLayout tk_lin;
    @BindView(R.id.book_lin)
    LinearLayout book_lin;
    @BindView(R.id.test_lin)
    LinearLayout test_lin;


    @BindView(R.id.shiting_text)
    TextView st_text;
    @BindView(R.id.bx_text)
    TextView bx_text;
    @BindView(R.id.tk_text)
    TextView tk_text;
    @BindView(R.id.book_text)
    TextView book_text;
    @BindView(R.id.pic_text)
    TextView pic_text;
    @BindView(R.id.test_text)
    TextView test_text;
    @BindView(R.id.plan_btn)
    Button btn;

    Unbinder unbinder;

    private LocalReceiver mReceiver;
    private IndexModel2 newIndex;//首页全部收据汇总
    private Gson gson = new Gson();

    private String yiji_name;
    private MaterialDialog dialog;
    private int lessontype = 1;
    CallBack call;
    private String tempdata = "";


    private BanXingAdapter banXingAdapter;
    private ShiTingAdapter shiTingAdapter;
    private TiKuAdapter tiKuAdapter;
    private HomeBookAdapter bookAdapter;
    private TestAdapter testAdapter;


    RoundedCorners roundedCorners = new RoundedCorners(20);
    //通过RequestOptions扩展功能
    RequestOptions options = RequestOptions.centerCropTransform().placeholderOf(R.mipmap.ic_launcher).bitmapTransform(roundedCorners).override(320, 440);
    RequestOptions options2 = RequestOptions.centerCropTransform().placeholderOf(R.mipmap.ic_launcher).bitmapTransform(roundedCorners);

    private Handler handler = null;


    public NewHomeFragment2() {

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        call = (CallBack) getActivity();
        handler = new Handler();


        //接收广播d'd
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction("fragment_home_left");
            mReceiver = new LocalReceiver();
            BroadCastManager.getInstance().registerReceiver(getActivity(),
                    mReceiver, filter);//注册广播接收者
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_new_home2, container, false);
        unbinder = ButterKnife.bind(this, view);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dorefresh();
                    }
                }, 1500);
            }
        });
        init();
        setbold();

        return view;

    }


    private void init() {

        refreshLayout.setEnableLoadMore(false);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new GlideImageLoader());
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3500);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });
        Glide.with(getActivity()).load(R.drawable.zige).apply(options)
                .into(zige);
        Glide.with(getActivity()).load(R.drawable.zixue).apply(options)
                .into(zixue);

        ViewGroup.LayoutParams params = banner.getLayoutParams();

        params.height = (int) (((DensityUtils.dp2px(getActivity(), (Constant.SCREEN_WIDTH - 20)) / 585.00)) * 300);
        banner.setLayoutParams(params);


        yiji_name = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";
        L.i("main", "yiji_name>>>>" + yiji_name);
        if (!"".equals(Tools.isNull(yiji_name))) {
            topTitle.setText(Tools.isNull(yiji_name));
        } else {
            topTitle.setText("自学考试");
        }
        if (null != dialog) {
            dialog.dismiss();
        }
        index_rel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tanchuang();
            }
        });
        topTitle.setFocusable(true);
        topTitle.setFocusableInTouchMode(true);
        topTitle.requestFocus();

        zige.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Constant.FLAG = 1;
                call.getData("课程");
            }
        });
        zixue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Constant.FLAG = 2;
                call.getData("课程");
            }
        });
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), TimeTableActivity.class);
                intent.putExtra("data", tempdata);
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });
        time_rel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), TimeTableActivity.class);
                intent.putExtra("data", tempdata);
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });

        //免费试听
        List<ShiTing> shiTingList = new ArrayList<>();
        shiTingAdapter = new ShiTingAdapter(getActivity(), R.layout.item_shiting, shiTingList);
        shitingGrid.setAdapter(shiTingAdapter);
        shitingGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ShiTing shiTing = (ShiTing) adapterView.getAdapter().getItem(i);
                HashMap<String, Object> map = new HashMap();
                map.put("id", shiTing.getId());
                map.put("title", shiTing.getTitle());
                map.put("type", shiTing.getType());
                ActivitySkipUtil.skipAnotherActivity(getActivity(), LessonDetailActivity.class, map);
            }
        });

        //班型
        List<LessonModel.DataBean> list = new ArrayList<>();
        banXingAdapter = new BanXingAdapter(getActivity(), R.layout.item_banxing, list);
        banxingGrid.setAdapter(banXingAdapter);
        banxingGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                LessonModel.DataBean bean = (LessonModel.DataBean) adapterView.getAdapter().getItem(i);
                HashMap<String, Object> map = new HashMap();
                map.put("id", bean.getId());
                map.put("title", bean.getTitle());
                map.put("type", bean.getType());
                ActivitySkipUtil.skipAnotherActivity(getActivity(), LessonDetailActivity.class, map);
            }
        });

        //题库
        List<CategoriesBean> list1 = new ArrayList<>();
        tiKuAdapter = new TiKuAdapter(getActivity(), R.layout.item_tiku, list1);
        tkgrid.setAdapter(tiKuAdapter);
        tkgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                CategoriesBean bean = (CategoriesBean) adapterView.getAdapter().getItem(i);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("id", bean.getId());
                map.put("title", bean.getName());
                ActivitySkipUtil.skipAnotherActivity(getActivity(), LianXiActivity.class, map);
            }
        });


        //图书
        List<BookBean> list2 = new ArrayList<>();
        bookAdapter = new HomeBookAdapter(getActivity(), R.layout.item_book, list2);
        bookgrid.setAdapter(bookAdapter);
        bookgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                BookBean bookBean = (BookBean) adapterView.getAdapter().getItem(i);
                HashMap<String, Object> params = new HashMap<>();
                params.put("id", bookBean.getId());
                ActivitySkipUtil.skipAnotherActivity(getActivity(), BookDetailActivity.class, params);
            }
        });
        //真题
        List<TestpapersBean> list3 = new ArrayList<>();
        testAdapter = new TestAdapter(getActivity(), R.layout.item_test, list3);
        testListView.setAdapter(testAdapter);
        testListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TestpapersBean bean = (TestpapersBean) adapterView.getAdapter().getItem(i);
                HashMap map = new HashMap();
                map.put("id", bean.getId());
                ActivitySkipUtil.skipAnotherForActivity(getActivity(), ExamActivity.class, map);
            }
        });


        bx_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);//防止多个产生
                intent.setClass(getActivity(), BanxingActivity.class);
                startActivity(intent);
            }
        });
        tk_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call.getData("题库");
            }
        });
        book_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);//防止多个产生
                intent.setClass(getActivity(), BookActivity.class);
                startActivity(intent);
            }
        });
        test_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivitySkipUtil.skipAnotherActivity(getActivity(), ZhenTiNewActivity.class, false);
            }
        });
        loadata();
    }


    private void loadata() {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        Async.post("tiku/home", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    newIndex = gson.fromJson(new String(responseBody), IndexModel2.class);

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }

            @Override
            public void onFinish() {
                if (newIndex.getSuccess().equals("1")) {
                    gettimetable();
                }
            }
        });
    }

    private void gettimetable() {
        RequestParams params = new RequestParams();
        params.add("userId", Constant.uid);
        params.add("token", Constant.token);
        Async.post("my/daycron", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    try {
                        Gson gson = new Gson();
                        TableModel result = gson.fromJson(new String(responseBody), TableModel.class);
                        //1表示红点，0表示灰点  //但是真实的数据时0红点 1灰点
                        if (1 == Tools.isIntNull(result.getSuccess())) {
                            if (!result.getLesson_date().equals("") && result.getLesson_date() != null) {
                                tempdata = result.getLesson_date();
                            }
                        }


                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }

            @Override
            public void onFinish() {
                final Handler handler = new IHandler();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = new Integer(1);
                        handler.sendMessage(msg);

                    }
                }).start();
            }
        });
    }


    // 顶部banner图
    private void initBanner() {
        L.i("ismain", String.valueOf(isMainThread()));
        List<String> imgList = new ArrayList<>();
        for (String str : newIndex.getBanners()) {
            imgList.add(str);
        }
        banner.setImages(imgList);
        banner.start();
        initshiting();
    }

    private void initshiting() {
        shiTingAdapter.addAll(newIndex.getShiting());
        shiTingAdapter.notifyDataSetChanged();
        initbanxing();
    }

    private void initbanxing() {
        banXingAdapter.addAll(newIndex.getBanxing());
        banXingAdapter.notifyDataSetChanged();
        inittiku();
    }

    private void inittiku() {
        tiKuAdapter.addAll(newIndex.getCategories());
        tiKuAdapter.notifyDataSetChanged();
        initbook();
    }

    private void initbook() {
        bookAdapter.addAll(newIndex.getBookdata());
        bookAdapter.notifyDataSetChanged();
        initpic();
    }

    private void initpic() {
        linearLayout.removeAllViews();
        for (int i = 0; i < newIndex.getTupian().size(); i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_pic, null);
            ImageView imageView = view.findViewById(R.id.pic_pic);
            Glide.with(getActivity()).load(newIndex.getTupian().get(i)).apply(options)
                    .into(imageView);
            linearLayout.addView(view);

        }
        inittest();


    }

    private void inittest() {
        testAdapter.addAll(newIndex.getTestpapers());
    }


    private class IHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
//                    Log.e(TAG, "handler:" + msg.obj);
                    initBanner();
                    break;
                default:
                    break;
            }
        }
    }

    private void setbold() {
        st_text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        bx_text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        tk_text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        book_text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        pic_text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        test_text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    }


    private void tanchuang() {

        if (null != dialog) {
            dialog.dismiss();
        }
        dialog = new MaterialDialog.Builder(getActivity())
                .customView(R.layout.fragment_index_top, false)
                .show();


        View customeView = dialog.getCustomView();
        TextView quxiao = customeView.findViewById(R.id.quxiao);
        TextView queding = customeView.findViewById(R.id.queding);

        //
        TextView kaoshiVal = customeView.findViewById(R.id.kaoshi_val);
        TextView xueduanVal = customeView.findViewById(R.id.xueduan_val);
        TextView xuekeVal = customeView.findViewById(R.id.xueke_val);


        String yiji_name = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";
        String erji_name = SharedPreferencesUtil.getData(getContext(), "erjiName", "") + "";
        String sanji_name = SharedPreferencesUtil.getData(getContext(), "sanjiName", "") + "";
        if (!"".equals(Tools.isNull(yiji_name))) {
            kaoshiVal.setText(Tools.isNull(yiji_name));
        } else {
            kaoshiVal.setText("自学考试");
        }
        if (!"".equals(Tools.isNull(erji_name))) {
            xueduanVal.setText(Tools.isNull(erji_name));
        } else {
            xueduanVal.setText(Tools.isNull("学前"));
        }
        if (!"".equals(Tools.isNull(sanji_name))) {
            xuekeVal.setText(Tools.isNull(sanji_name));
        } else {
            xuekeVal.setText(Tools.isNull("数学"));
        }

        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.hide();
            }
        });

        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != dialog) {
                    dialog.dismiss();
                }

                Constant.IS_EDIT_CHANAGE = "IndexFragment";

                ActivitySkipUtil.skipAnotherActivity(getActivity(), SubjectMoreActivity.class, false);
            }
        });
    }


    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //收到广播后的处理
            dorefresh();

        }

    }

    private void dorefresh() {
        yiji_name = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";
        L.i("main", "yiji_--------------name>>>>" + yiji_name);
        if (!"".equals(Tools.isNull(yiji_name))) {
            topTitle.setText(Tools.isNull(yiji_name));
        } else {
            topTitle.setText("自学考试");
        }
        if ("教师资格证".equals(yiji_name)) {
            lessontype = 1;
        } else {
            lessontype = 2;
        }

        newIndex = new IndexModel2();
        banXingAdapter.clear();
        shiTingAdapter.clear();
        tiKuAdapter.clear();
        bookAdapter.clear();
        testAdapter.clear();
        loadata();
        refreshLayout.finishRefresh();
    }


    public interface CallBack {
        void getData(String str);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    public boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }
}
